layui.use(['admin', 'ax', 'table', 'treetable'], function () {
    var $ax = layui.ax;
    var admin = layui.admin;
    var table = layui.table;
    var treetable = layui.treetable;

    var Current = {
        tableId: "table"
    };

    /**
     * 初始化表格的列
     */
    Current.initColumn = function () {
        return [[
            {type: 'numbers'},
            {field: 'id', hide: true, sort: true, title: 'id'},
            {field: 'name', sort: true, title: '菜单名称'},
            {field: 'url', sort: true, title: '请求地址'},
            {field: 'sort', sort: true, title: '排序'},
            {field: 'menuFlag', sort: true, title: '是否是菜单' ,templet: function (d) {
                    return d.menuFlag == 0 ? "否" : "是";
                }
            },
            {field: 'status', sort: true, title: '状态' ,templet: function (d) {
                    return d.status == 0 ? "禁用" : "启用";
                }
            },
            {field: 'description', sort: true, title: '描述'},
            {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 200}
        ]];
    };

    Current.onClick = function (e, treeId, treeNode) {
        Current.search();
    };

    Current.search = function () {
        var queryData = {};
        table.reload(Current.tableId, {where:queryData});
    };

    Current.onEdit = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '编辑菜单',
            area: ['60%','70%'],
            content: system.contextPath + '/admin/menu/toEdit?id=' + data.id,
            end: function () {
                if(admin.getTempData('formOk')){
                    reloadTableAndLocation(data.id);
                }
            }
        });
    };

    function reloadTableAndLocation(id){
        //记录表格位置
        var scrollTop=0;
        var layuiTable = $('.layui-table-main');

        if(layuiTable!=null&&layuiTable.length>0){
            scrollTop = layuiTable[0].scrollTop;
        }

        //重载表格
        Current.initTable(Current.tableId);

        //这里必须使用setTimeout ，跳转记录位置
        setTimeout(function(){
            //打开树节点
            var targetArray = new Array();
            var inId = id;
            while( inId && inId != 0){
                var $target = $($.find("[lay-tid="+inId+"]"));
                inId = $target.attr("lay-tpid");
                targetArray.push($target);
            }

            for(var i = targetArray.length -1 ;i >=0 ;--i){
                targetArray[i].click();
            }

            //跳转位置
            if(layuiTable!=null&&layuiTable.length>0){
                $('.layui-table-main').scrollTop(scrollTop)
            }
        },300)
    }

    Current.onAdd = function (data) {
        var id = data ? data.id : 0;

        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '添加',
            area: ['60%','70%'],
            content: system.contextPath + '/admin/menu/toAdd?id=' + id,
            end: function () {
                if(admin.getTempData('formOk')){
                    reloadTableAndLocation(id);
                }
            }
        });
    };

    Current.onDelete = function (data) {
        var operation = function () {
            var ajax = new $ax(system.contextPath + "/admin/menu/delete/id/" + data.id, function (res) {
                if(res.status){
                    system.success("删除成功!");
                    Current.initTable(Current.tableId);
                }else{
                    system.error("删除失败!" + res.msg + "!");
                }
            }, function (res) {
                system.error("删除失败!" + res.msg + "!");
            });
            ajax.start();
        };
        system.confirm("是否删除菜单" + data.name + "?", operation);
    };

    /**
     * 初始化表格
     */
    Current.initTable = function (tableId, data) {
        return treetable.render({
            elem: '#' + tableId,
            url: system.contextPath + '/admin/menu/search/all',
            where: data,
            page: false,
            height: "full-158",
            cellMinWidth: 100,
            cols: Current.initColumn(),
            treeColIndex: 2,
            treeSpid: "0",
            treeIdName: "id",
            treePidName: "pid",
            treeDefaultClose: true,
            treeLinkage: false
            ,isJump: true //是否允许点击节点时弹出新窗口跳转
            ,showLine: true  //是否开启连接线
        });
    };

    // 渲染表格
    var tableResult = Current.initTable(Current.tableId);

    $('#expandAll').click(function () {
        treetable.expandAll('#' + Current.tableId);
    });

    $('#foldAll').click(function () {
        treetable.foldAll('#' + Current.tableId);
    });

    $('#btnAdd').click(function () {
        Current.onAdd();
    });

    // 工具条点击事件
    table.on('tool(' + Current.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Current.onEdit(data);
        } else if (layEvent === 'delete') {
            Current.onDelete(data);
        } else if (layEvent === 'add') {
            Current.onAdd(data);
        }
    });
});
